#include <bits/stdc++.h>
using namespace std;
#define int long long

int jiecheng(int a,int mod)
{
	int sum=1;
	for(int i=1;i<=a;i++)
	{
		sum=sum*i%mod;
	}
	return sum;
}

signed main()
{
	ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);

	int t;
	cin >> t;
	while(t--)
	{
		char c1,c2,c3,c4,c5;
		int a,b,mod;
		cin >> c1 >> a >> c2 >> c3 >> b >> c4 >> c5 >> mod;
		int sum1=jiecheng(a,mod);
		int sum=(sum1+b)%mod;
		cout << sum << endl;
	}
    return 0;
}

